package com.hcg.distributedtx.config.datasource;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.hcg.distributedtx.config.db.DBConfigCm;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.hcg.distributedtx.mapper.cm"/*"com.hcg.distributedtx.cm"*/,sqlSessionTemplateRef = "cmSqlSessionTemplate")
public class CmDataSourceConfig {

    // 配置数据源
    @Bean("cmDataSource")
    public DataSource cmDataSource(DBConfigCm dbConfigCm) throws Exception{
        MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
        mysqlXADataSource.setURL(dbConfigCm.getJdbc_url());
        mysqlXADataSource.setPinGlobalTxToPhysicalConnection(true);
        mysqlXADataSource.setPassword(dbConfigCm.getPassword());
        mysqlXADataSource.setUser(dbConfigCm.getUsername());
        mysqlXADataSource.setPinGlobalTxToPhysicalConnection(true);

        // 创建 Atomikos 全局事务，并将本地事务注册进去
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        atomikosDataSourceBean.setXaDataSource(mysqlXADataSource);
        atomikosDataSourceBean.setUniqueResourceName("cmDataSource");

        atomikosDataSourceBean.setMinPoolSize(dbConfigCm.getMinPooSize());
        atomikosDataSourceBean.setMaxPoolSize(dbConfigCm.getMaxPooSize());
        atomikosDataSourceBean.setMaxLifetime(dbConfigCm.getMaxLifetime());
        atomikosDataSourceBean.setBorrowConnectionTimeout(dbConfigCm.getBoorowConnectionTimeout());
        atomikosDataSourceBean.setLoginTimeout(dbConfigCm.getLoginTimeout());
        atomikosDataSourceBean.setMaintenanceInterval(dbConfigCm.getMaintenanceInterval());
        atomikosDataSourceBean.setMaxIdleTime(dbConfigCm.getMaxIdleTime());
        atomikosDataSourceBean.setTestQuery(dbConfigCm.getTestQuery());

        return atomikosDataSourceBean;
    }

    @Bean(name = "cmSqlSessionFactory")
    public SqlSessionFactory cmSqlSessionFactory(@Qualifier("cmDataSource") DataSource cmDataSource)throws Exception{
        SqlSessionFactoryBean  bean = new SqlSessionFactoryBean();
        bean.setDataSource(cmDataSource);
        return  bean.getObject();
    }

    @Bean(name = "cmSqlSessionTemplate")
    public SqlSessionTemplate cmSqlSessionTemplate(@Qualifier("cmSqlSessionFactory") SqlSessionFactory cmSqlSessionFactory)throws Exception{
        return new SqlSessionTemplate(cmSqlSessionFactory);
    }



}
